<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="800px"
    @ok="handleSubmit"
  >
    <RulesView :rules="rules" ref="rulesRef" :typeCode="typeCode" :formCode="formCode" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useMessage } from '/@/hooks/web/useMessage';
  import RulesView from './rulesView/index.vue';
  import { isArray, isString } from '/@/utils/is';

  export default defineComponent({
    components: {
      BasicDrawer,
      RulesView,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage } = useMessage();
      let dataRef = ref<any>({});
      const rules = ref([]);
      const rulesRef = ref<HTMLElement | null>(null);
      const typeCode = ref('');
      const formCode = ref('');
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        setDrawerProps({ confirmLoading: false });
        typeCode.value = data.typeCode || '';
        formCode.value = data.formCode || '';
        dataRef.value = {};
        rules.value = [];
        if (isArray(data.rules)) {
          rules.value = data.rules;
        } else if (isString(data.rules)) {
          rules.value = JSON.parse(data.rules);
        }
      });

      const getTitle = '提交规则设置';

      async function handleSubmit() {
        try {
          setDrawerProps({ confirmLoading: true });
          const params = {
            rules: [],
          };
          if (rulesRef.value) {
            params.rules = rulesRef.value.list;
          }
          // createMessage.success('操作成功');
          closeDrawer();
          emit('success', params);
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      const handleRoleNames = (val, node) => {
        const { dataRef: newDataRef } = node;
        dataRef.value.roleDescs = val;
        dataRef.value.roleCodes = newDataRef['codes'];
      };

      return {
        registerDrawer,
        getTitle,
        handleSubmit,
        dataRef,
        handleRoleNames,
        rules,
        rulesRef,
        typeCode,
        formCode,
      };
    },
  });
</script>
<style lang="less" scoped></style>
